import 'dart:async';

import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

import '../../utils/global_util.dart';
import '../../utils/http_util.dart';

class LoginViewmodel extends GetxController {
  var chooseIndex = 0.obs;
  var hasChoose = false.obs;
  var openShow = false.obs;
  var countDown = 0.obs;
  Timer? timer;

  changeIndex(int index) {
    chooseIndex.value = index;
  }

  changeChoose() {
    hasChoose.value = !hasChoose.value;
  }

  changeOpenShow() {
    openShow.value = !openShow.value;
  }

  Future<void> querySms(String phone) async {
    EasyLoading.show(status: 'loading', maskType: EasyLoadingMaskType.clear);
    try {
      final result = await HttpUtil().post(
        'send/mobile/login',
        params: {"mobile": phone},
      );
      final dynamic responseData = result.data['data']; // 明确类型声明
      final String? token = responseData['token'] as String?;
      countDown.value = 60;
      startTime();
    } catch (e) {
      EasyLoading.showToast('请求失败');
    }
    EasyLoading.dismiss();
  }

  startTime() {
    if (timer != null) {
      stopTimer();
    }
    void callback() {
      if (countDown.value > 0) {
        countDown.value -= 1;
      } else if (countDown.value == 0) {
        stopTimer();
      }
    }
    timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
      callback();
    });
  }

  stopTimer() {
    timer!.cancel();
    timer = null;
  }

  Future<void> queryLogin(String account, String password) async {
    EasyLoading.show(status: 'loading', maskType: EasyLoadingMaskType.clear);
    try {
      final result = await HttpUtil().post(
        'login/mobile',
        params: {"mobile": account, "mobile_code": password},
      );
      final dynamic responseData = result.data['data']; // 明确类型声明
      final String? token = responseData['token'] as String?;
      GlobalUtil.login(token ?? '');
    } catch (e) {
      EasyLoading.showToast('请求失败');
    }
    EasyLoading.dismiss();
  }

  Future<void> querySmsLogin(String phone, String sms) async {
    EasyLoading.show(status: 'loading', maskType: EasyLoadingMaskType.clear);
    try {
      final result = await HttpUtil().post(
        'login/mobile',
        params: {"mobile": phone, "mobile_code": sms},
      );
      final dynamic responseData = result.data['data']; // 明确类型声明
      final String? token = responseData['token'] as String?;
      GlobalUtil.login(token ?? '');
    } catch (e) {
      EasyLoading.showToast('请求失败');
    }
    EasyLoading.dismiss();
  }
}
